package com.base.mail;

import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.base.BaseApp;
import com.base.commonlib.base.CBaseBarActivity;
import com.base.commonlib.bean.User;
import com.base.commonlib.http.RealNetWorkUtil;
import com.base.commonlib.http.utils.CallBackImpl;
import com.base.commonlib.http.utils.ErrorLogUtil;
import com.base.commonlib.sp.SpUtil;
import com.base.commonlib.utils.RxBus2;
import com.base.commonlib.utils.ToastUtil;
import com.base.mail.adapter.OrganAdapter;
import com.base.mail.adapter.StructureAdapter;
import com.base.mail.bean.PartListBean;
import com.base.mail.databinding.ActivityOrganBinding;
import com.base.mail.tree.Node;
import com.base.mail.tree.OnTreeNodeClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * 组织架构
 * Created by weikailiang on 2019/5/31.
 */
@Route(path = "/mail/structure")
public class StructureActivity extends CBaseBarActivity {
    protected ActivityOrganBinding mBinding;
    protected CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    StructureAdapter mAdapter;

    @Autowired
    public String token;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_organ;
    }

    @Override
    protected void init() {
        super.init();
        mBinding = (ActivityOrganBinding) mRootBinding;
    }

    @Override
    protected void start() {
        setBackNavigation();
        setBarTitle("组织架构");
        getData("");
        setRigImg(R.drawable.ic_title_save, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(mBinding.etName.getText().toString())) {
                    ToastUtil.show("请输入姓名");
                    return;
                }
//                if (TextUtils.isEmpty(mBinding.etIdcard.getText().toString())) {
//                    ToastUtil.show("请输入身份证号");
//                    return;
//                }
//                if (mBinding.etIdcard.getText().toString().length() != 18) {
//                    ToastUtil.show("身份证号格式不正确");
//                    return;
//                }
                if (TextUtils.isEmpty(StructureAdapter.CHECKID)) {
                    ToastUtil.show("请选择");
                    return;
                }
                initStruct(StructureAdapter.CHECKID);
            }
        });


        mBinding.etDeptName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {


            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s)) {
                    getData(s.toString());
                } else {
                    getData("");
                }
            }
        });

    }


    private void getData(String str){
        showPb();
        HashMap<String, Object> param = new HashMap<>();
        param.put("name",str);
        Disposable enqueue = RealNetWorkUtil.get().method("api-auth/user/deptTree").params(param)
                .build().enqueueForArray(PartListBean.class, new CallBackImpl<List<PartListBean>>() {
                    @Override
                    public void onError(int code, String msg, String errMsg) {
                        hidePb();
                    }

                    @Override
                    public void onNext(List<PartListBean> users) {
                        hidePb();
                        parse(users);
                    }
                });

        mCompositeDisposable.add(enqueue);
    }

    private void parse(List<PartListBean> list) {
        List<Node> mData = new ArrayList<>();
        Node node = null;
        for (PartListBean bean : list) {
            node = new Node();
            node.setId(bean.getId());
            node.setpId(bean.getParentId());
            node.setName(bean.getName());
            node.setState(bean.getType() + "");
            if (!TextUtils.isEmpty(bean.getPhone())) {
                node.setPhone(bean.getPhone());
            }
            mData.add(node);
        }
        mBinding.recycler.setLayoutManager(new LinearLayoutManager(this));
        //第一个参数  RecyclerView
        //第二个参数  上下文
        //第三个参数  数据集
        //第四个参数  默认展开层级数 0为不展开
        //第五个参数  展开的图标
        //第六个参数  闭合的图标
        if (mAdapter==null){
            mAdapter = new StructureAdapter(mBinding.recycler, mContext,
                    mData, 1);
            mBinding.recycler.setAdapter(mAdapter);
            mAdapter.setOnTreeNodeClickListener(new OnTreeNodeClickListener() {
                @Override
                public void onClick(Node node, int position) {

                }
            });
        }else {
            mAdapter.addDataAll(mData,1);
            mAdapter.notifyDataSetChanged();
        }


    }

    private void initStruct(String nodeid) {
        showPb();
        HashMap<String, String> param = new HashMap<>();
        param.put("userId", BaseApp.getUser().getUserId());
        param.put("deptId", nodeid);
       // param.put("idCard", mBinding.etIdcard.getText().toString());
        param.put("userName", mBinding.etName.getText().toString());
        Disposable enqueue = RealNetWorkUtil.postContent().method("api-auth/user/update").content(param)
                .build().enqueue(User.class, new CallBackImpl<User>() {
                    @Override
                    public void onError(int code, String msg, String errMsg) {
                        ToastUtil.show("出错了");
                        hidePb();
                    }

                    @Override
                    public void onNext(User user) {
                        hidePb();
                        BaseApp.saveUser(user);
                        SpUtil.setToken(token);
                        ARouter.getInstance().build("/study/home")
                                .withInt("num", 2)
                                .navigation(mContext, new NavCallback() {
                                    @Override
                                    public void onArrival(Postcard postcard) {
                                        finish();
                                        RxBus2.getInstance().post(new User());
                                    }
                                });
                    }
                });

        mCompositeDisposable.add(enqueue);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCompositeDisposable != null && mCompositeDisposable.isDisposed()) {
            mCompositeDisposable.dispose();
        }
    }
}
